package cn.edu.lingnan.servlet;

import cn.edu.lingnan.dao.StudentDaoMysqlImpl;
import cn.edu.lingnan.pojo.Student;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        //1 从页面获取表单中提交的数据，使用getParameter()方法，建议参数名与数据库一致
        String sname = req.getParameter("sname");
        String spassword = req.getParameter("spassword");
        //建议使用输出语句输出读取参数的结果，不仅仅是看读到内容没有，还要看对不对，比如是否有中文乱码
        System.out.println("[Debug]sname and spassword value is " + sname + "   " + spassword);

        //2  调用业务逻辑,一种是调用service中类的方法，另一种是其他，比如注销
        StudentDaoMysqlImpl service = new StudentDaoMysqlImpl();
        Student student = service.findStudentByNameAndPassword(sname,spassword);
        HttpSession session = req.getSession();
        session.setAttribute("right",student.getSright());
        if (student.getSright()==1) {
            session.setAttribute("sname",sname);
            session.setAttribute("sright","管理员");

        }else {
            session.setAttribute("sname",sname);
            session.setAttribute("sright","学生");
        }




        //3  依据返回结果，返回到相应的用户页面
        if (student.getSid()!=null){
            resp.sendRedirect("/main.jsp");
        }else {
            resp.sendRedirect("/error.html");

        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doGet(req,resp);
    }
}
